import { MciDatePicker, MciInput, MciSelect } from '@/components/base';
import { IOption, mciSelectEmits, mciSelectProps } from '@/components/base/Select';
import { useDictStore } from '@/store/dict';
import { PropType } from 'vue';
// import { FieldTypeSelector } from '../FieldType';
import { ICalcTypeWithValueSelectorValue } from './type';
import { ExpValue } from '../ExpValue';
import { useFormMode } from '@/components/base/Form/mode';
import { VarType } from '../../Nodes/DataLoad/components/DataSet/type';
import { IGetDecisionFlowSystemVarsRes } from '@/api/decision-engine';

type EnumOptionType = IGetDecisionFlowSystemVarsRes[number]['options']; // java里即代表int和string的只能用Object
type TVariableOptions = IOption & { varType?: string; options: EnumOptionType };

export const CalcTypeSelector = defineComponent<Partial<InstanceType<typeof MciSelect>>>({
  setup() {
    const { dictCalcTypeOptions } = useDictStore();
    return () => {
      return <MciSelect list={dictCalcTypeOptions} placeholder="请选择值来源" />;
    };
  }
});

export const CalcTypeWithValueSelector = defineComponent({
  props: {
    ...mciSelectProps,
    modelValue: {
      type: Object as PropType<ICalcTypeWithValueSelectorValue>,
      default: () => ({})
    },
    variableOptions: {
      type: Array as PropType<TVariableOptions[]>,
      default: () => []
    },
    withFieldType: {
      type: Boolean,
      default: false
    },
    varType: {
      type: String,
      default: ''
    },
    left: {
      type: String,
      default: ''
    },
    fieldTypeDisabled: {
      type: Boolean,
      default: false
    }
  },
  emits: [...mciSelectEmits],
  setup(props, { emit }) {
    const formMode = useFormMode();
    const { dictCalcTypeOptions } = useDictStore();
    const variableType = ref(props.varType);
    const valueTypeOptons = computed(() => {
      if (variableType.value === VarType.Enum || variableType.value === VarType.Date || variableType.value === VarType.DateTime) {
        const result: any[] = [];
        dictCalcTypeOptions.forEach((item) => {
          if (item.value === 'CONSTANT') {
            result.push({
              ...item
            });
          }
        });
        return result;
      } else {
        return dictCalcTypeOptions;
      }
    });
    const dateVal = ref(props.modelValue?.value);

    watch(
      () => [props.varType],
      () => {
        variableType.value = props.varType;
      },
      { immediate: true, deep: true }
    );

    return () => {
      const calcType = props.modelValue?.calcType;
      let fieldType = props.modelValue?.fieldType;
      let varType = variableType.value;
      //  type EnumOptionElementType = EnumOptionType extends (infer U)[] ? U : {
      //   key: object;
      //   value: object;
      //  };
      const enumOptions = ref<IOption[]>([]);

      watch(
        () => [() => variableType],
        () => {
          varType = variableType.value;
          if (calcType === 'CONSTANT' && variableType.value) {
            fieldType = variableType.value;
          }
        },
        { immediate: true, deep: true }
      );
      watch(
        () => [() => props.left],
        () => {
          if (variableType.value === VarType.Enum && props.left) {
            const target = props.variableOptions.find((item) => item.value === props.left);

            enumOptions.value =
              target?.options?.map((item) => {
                return {
                  label: item.key! as string,
                  value: item.value! as string
                };
              }) || [];
          } else {
            enumOptions.value = [];
          }
        },
        { immediate: true, deep: true }
      );
      return (
        <div class="flex gap-8 shrink-0 grow" style={{ width: '100%' }}>
          <MciSelect
            class={{ 'shrink-0': true, 'w-100': formMode?.mode === 'edit' }}
            modelValue={calcType}
            onUpdate:modelValue={(val: string) => {
              if (val === 'CONSTANT' && varType) {
                fieldType = varType;
              }
              emit('update:modelValue', { calcType: val, value: '', fieldType });
            }}
            list={valueTypeOptons.value}
            placeholder="请选择值来源"
          />
          {calcType === 'CONSTANT' &&
            (varType === VarType.Enum ? (
              <MciSelect
                class="grow"
                v-model={props.modelValue.value}
                filterable
                list={enumOptions.value}
                onChange={(val: string) => {
                  emit('update:modelValue', { calcType, value: val, fieldType });
                }}
              />
            ) : varType === VarType.Date ? (
              <MciDatePicker
                class="grow"
                mode={formMode?.mode}
                v-model={dateVal.value}
                type={'date'}
                format="YYYY-MM-DD"
                placeholder={'请选择日期'}
                onChange={(val: Date) => {
                  emit('update:modelValue', { calcType, value: val?.getTime(), fieldType });
                }}
              />
            ) : varType === VarType.DateTime ? (
              <MciDatePicker
                class="grow"
                mode={formMode?.mode}
                v-model={dateVal.value}
                type={'datetime'}
                format={'YYYY-MM-DD HH:mm:ss'}
                placeholder={'请选择时间'}
                onChange={(val: Date) => {
                  emit('update:modelValue', { calcType, value: val?.getTime(), fieldType });
                }}
              />
            ) : (
              <MciInput
                class="grow"
                key="CONSTANT"
                onInput={(val: string) => {
                  emit('update:modelValue', { calcType, value: val, fieldType });
                }}
                v-model={props.modelValue.value}
                placeholder="请输入值"
              />
            ))}
          {calcType === 'VARIABLE' && (
            <MciSelect
              style={{ width: '100%' }}
              filterable
              key="VARIABLE"
              modelValue={props.modelValue.value}
              onChange={(value) => {
                const fieldType = props.variableOptions.find((item) => item.value === value)?.varType;
                emit('update:modelValue', { calcType, value, fieldType });
              }}
              list={props.variableOptions}
              placeholder="请选择变量列表"
            />
          )}
          {calcType === 'EXPRESSION' && (
            <ExpValue
              cond-value={props.modelValue.value}
              onValue-change={(val: string) => {
                emit('update:modelValue', { calcType, value: val, fieldType });
              }}
            />
          )}
        </div>
      );
    };
  }
});
